/**
 * Copyright (c) 2006-2016 Huize Ltd. All Rights Reserved. 
 *  
 * This code is the confidential and proprietary information of   
 * Hzins. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with Huize,http://www.huize.com.
 *  
 */
package com.agan.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author hz1412988
 * @date 2018年2月9日 下午5:15:22
 * @version
 */
public class TryLockTest extends Thread {

    public static ReentrantLock lock = new ReentrantLock();

    public TryLockTest(String name) {
	super(name);
    }

    @Override
    public void run() {
	try {
	    if (lock.tryLock(5, TimeUnit.SECONDS)) {
		Thread.sleep(6000);
	    } else {
		System.out.println(this.getName() + " get lock failed");
	    }
	} catch (Exception e) {
	} finally {
	    if (lock.isHeldByCurrentThread()) {// 查询当前线程是否保持此锁定
		System.out.println("lock.isHeldByCurrentThread: " + this.getName());
		lock.unlock();
	    }
	}
    }

    public static void main(String[] args) {
	TryLockTest t1 = new TryLockTest("TryLockTest1");
	TryLockTest t2 = new TryLockTest("TryLockTest2");

	t1.start();
	t2.start();
    }

}
